package com.guodefu.sensitive.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.guodefu.sensitive.annotation.Sensitive;

import java.beans.Introspector;
import java.io.IOException;

public class SensitiveSerializer extends JsonSerializer<String> {

    private final Sensitive sensitive;
    private final SensitiveStrategyContext strategyContext;

    public SensitiveSerializer(Sensitive sensitive, SensitiveStrategyContext strategyContext) {
        this.sensitive = sensitive;
        this.strategyContext = strategyContext;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        Class<? extends SensitiveStrategy> type = sensitive.type();
        String beanName = Introspector.decapitalize(type.getSimpleName());
        SensitiveStrategy strategy = strategyContext.getStrategy(beanName);
        String maskedValue = strategy.getMaskedValue(value,
                sensitive.maskString());
        gen.writeString(maskedValue);
    }
}
